package com.renjian.funplaypro.utils;

import cn.hutool.json.JSONUtil;
import com.renjian.funplaypro.model.UserMessage;
import com.renjian.funplaypro.services.UserMessageService;
import com.renjian.funplaypro.services.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Gjing
 * type:0->单点客户端,1->群组客户端
 **/
@ServerEndpoint("/chat/{id}")
@Component
@Slf4j
public class MyWebsocketServer {
    public static UserMessageService chatMessageService;
    public static UserService userService;
    /**
     * 存放所有在线的单点客户端
     */

    private static Map<Long, Session> clients = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session,@PathParam("id")Long id) {
        log.info("有新的客户端连接了: {}", id);
        //将新用户存入在线的组
        clients.put(id, session);
    }

    /**
     * 客户端关闭
     * @param session session
     */
    @OnClose
    public void onClose(Session session,@PathParam("id")Long id) {

        log.info("有用户断开了, id为:{}", id);
        //将掉线的用户移除在线的组里
        clients.remove(id);
    }

    /**
     * 发生错误
     * @param throwable e
     */
    @OnError
    public void onError(Throwable throwable) {
        throwable.printStackTrace();
    }

    /**
     * 收到客户端发来消息
     * @param message  消息对象
     */
    @OnMessage
    public void onMessage(String message,@PathParam("id")Long id) {
        //start : 0->单点,1->群组
        message=message.trim();
        log.info("服务端收到客户端发来的消息: {}", message);
        String[] mess=message.split("\\|");
//        ChatMessage chat=new ChatMessage();
        UserMessage chat = JSONUtil.toBean(mess[2], UserMessage.class);
        CompletableFuture.runAsync(()->{
            chatMessageService.save(chat);
        },RExecutorUtil.getExecutor());
        chat.setUser(userService.getById(chat.getToUserId()));
        this.sendMsg(JSONUtil.toJsonStr(chat),chat.getToUserId());
    }

    /**
     * 群发消息
     * @param message 消息内容
     */
    private void sendMsg(String message,Long toUserId) {
        for (Map.Entry<Long, Session> sessionEntry : clients.entrySet()) {
            if(sessionEntry.getKey().equals(toUserId)){
                sessionEntry.getValue().getAsyncRemote().sendText(message);
                log.info("发送消息成功: {}", message);
                return;
            }
        }
    }
}
